/**
 * 设备连接状态组件
 * 
 * 用途：显示蓝牙设备连接状态和数据采集信息
 * 方法：使用Jetpack Compose构建状态显示UI
 * 原理：
 * - 显示设备连接状态（已连接/未连接）
 * - 显示数据采集状态和统计信息
 * - 通过定时器实时更新数据显示
 */

package com.example.brain_wave.ui.components

import androidx.compose.animation.core.*
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Bluetooth
import androidx.compose.material.icons.filled.BluetoothDisabled
import androidx.compose.material.icons.filled.Wifi
import androidx.compose.material.icons.filled.Bedtime
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.delay

/**
 * 设备连接状态组件
 */
@Composable
fun DeviceConnectionStatus(
    roomId: String?,  // 选中的房间ID
    currentUserState: UserState,  // 当前用户状态
    isConnected: Boolean,  // 实际连接状态
    modifier: Modifier = Modifier
) {
    // 信号质量和连接中状态管理
    var signalQuality by remember { mutableStateOf(0) }
    var isConnecting by remember { mutableStateOf(false) }
    
    // 动画状态
    val pulseAnimation by rememberInfiniteTransition().animateFloat(
        initialValue = 0.8f,
        targetValue = 1.2f,
        animationSpec = infiniteRepeatable(
            animation = tween(1000, easing = EaseInOut),
            repeatMode = RepeatMode.Reverse
        )
    )
    
    // 模拟连接过程
    LaunchedEffect(roomId, isConnected) {
        if (roomId != null && !isConnected) {
            isConnecting = true
            delay(2000) // 模拟连接时间
            isConnecting = false
        } else {
            isConnecting = false
        }
    }
    
    // 模拟信号质量变化
    LaunchedEffect(isConnected) {
        if (isConnected) {
            while (isConnected) {
                signalQuality = StoreRoomUtils.generateRandomSignalQuality()
                delay(3000) // 每3秒更新一次信号质量
            }
        }
    }
    
    Card(
        modifier = modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = Color(0xFF2A2A2A)
        ),
        shape = RoundedCornerShape(12.dp)
    ) {
        Column(
            modifier = Modifier.padding(8.dp), // 减少内边距从12dp到8dp
            verticalArrangement = Arrangement.spacedBy(6.dp) // 减少间距从8dp到6dp
        ) {
            // 标题
            Text(
                text = "设备连接状态",
                style = MaterialTheme.typography.titleSmall, // 使用更小的标题
                color = Color.White,
                fontWeight = FontWeight.Bold
            )
            
            // 连接状态显示
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(6.dp), // 减少间距
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 连接状态图标
                Box(
                    modifier = Modifier
                        .size(if (isConnecting) (24.dp * pulseAnimation) else 24.dp)
                        .clip(CircleShape)
                        .background(
                            when {
                                isConnecting -> Color(0xFFFFA726)
                                isConnected -> Color(0xFF4CAF50)
                                else -> Color(0xFFF44336)
                            }
                        ),
                    contentAlignment = Alignment.Center
                ) {
                    Icon(
                        imageVector = when {
                            isConnected -> Icons.Default.Bluetooth
                            isConnecting -> Icons.Default.Wifi
                            else -> Icons.Default.BluetoothDisabled
                        },
                        contentDescription = null,
                        tint = Color.White,
                        modifier = Modifier.size(16.dp) // 减少图标大小
                    )
                }
                
                // 连接状态文字
                Column(
                    modifier = Modifier.weight(1f),
                    verticalArrangement = Arrangement.spacedBy(2.dp) // 减少间距
                ) {
                    Text(
                        text = when {
                            isConnecting -> "正在连接..."
                            isConnected -> "已连接"
                            roomId != null -> "连接失败"
                            else -> "未选择房间"
                        },
                        color = when {
                            isConnecting -> Color(0xFFFFA726)
                            isConnected -> Color(0xFF4CAF50)
                            else -> Color(0xFFF44336)
                        },
                        style = MaterialTheme.typography.bodySmall, // 使用更小的字体
                        fontWeight = FontWeight.Medium
                    )
                    
                    if (roomId != null) {
                        Text(
                            text = "房间: $roomId",
                            color = Color.Gray,
                            style = MaterialTheme.typography.bodySmall,
                            fontSize = 11.sp // 使用更小的字体
                        )
                    }
                }
            }
            
            // 信号质量显示（仅在连接时显示）
            if (isConnected) {
                SignalQualityDisplay(
                    signalQuality = signalQuality,
                    modifier = Modifier.fillMaxWidth()
                )
            }
            
            // 当前睡眠状态显示
            CurrentSleepStateDisplay(
                userState = currentUserState,
                modifier = Modifier.fillMaxWidth()
            )
        }
    }
}

/**
 * 信号质量显示组件
 */
@Composable
private fun SignalQualityDisplay(
    signalQuality: Int,
    modifier: Modifier = Modifier
) {
    val qualityLevel = SleepStateStatistics(signalQuality = signalQuality).getSignalQualityLevel()
    
    Card(
        modifier = modifier,
        colors = CardDefaults.cardColors(
            containerColor = Color(0xFF1A1A1A)
        ),
        shape = RoundedCornerShape(8.dp)
    ) {
        Column(
            modifier = Modifier.padding(12.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.Wifi,
                        contentDescription = "信号质量",
                        tint = qualityLevel.color,
                        modifier = Modifier.size(20.dp)
                    )
                    
                    Text(
                        text = "信号质量",
                        color = Color.White,
                        fontSize = 14.sp,
                        fontWeight = FontWeight.Medium
                    )
                }
                
                Text(
                    text = qualityLevel.displayName,
                    color = qualityLevel.color,
                    fontSize = 12.sp,
                    fontWeight = FontWeight.Bold
                )
            }
            
            Spacer(modifier = Modifier.height(8.dp))
            
            // 信号质量进度条
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(6.dp)
                    .clip(RoundedCornerShape(3.dp))
                    .background(Color(0xFF333333))
            ) {
                Box(
                    modifier = Modifier
                        .fillMaxHeight()
                        .fillMaxWidth((200 - signalQuality) / 200f) // 信号质量越低，进度条越满
                        .clip(RoundedCornerShape(3.dp))
                        .background(qualityLevel.color)
                )
            }
            
            Spacer(modifier = Modifier.height(4.dp))
            
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Text(
                    text = "质量值: $signalQuality",
                    color = Color(0xFFBBBBBB),
                    fontSize = 10.sp
                )
                Text(
                    text = "0最佳 • 200最差",
                    color = Color(0xFF666666),
                    fontSize = 10.sp
                )
            }
        }
    }
}

/**
 * 当前睡眠状态显示组件
 */
@Composable
private fun CurrentSleepStateDisplay(
    userState: UserState,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier,
        colors = CardDefaults.cardColors(
            containerColor = Color(0xFF1A1A1A)
        ),
        shape = RoundedCornerShape(8.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(12.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                Icon(
                    imageVector = Icons.Default.Bedtime,
                    contentDescription = "睡眠状态",
                    tint = userState.color,
                    modifier = Modifier.size(20.dp)
                )
                
                Text(
                    text = "当前状态",
                    color = Color.White,
                    fontSize = 14.sp,
                    fontWeight = FontWeight.Medium
                )
            }
            
            // 状态指示器
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                Box(
                    modifier = Modifier
                        .size(12.dp)
                        .clip(CircleShape)
                        .background(userState.color)
                )
                
                Text(
                    text = userState.displayName,
                    color = userState.color,
                    fontSize = 14.sp,
                    fontWeight = FontWeight.Bold
                )
            }
        }
    }
}